<?php
declare (strict_types = 1);

namespace app;

use thans\jwt\facade\JWTAuth;
use think\Facade\Db;

class Before
{
    public function handle($request, \Closure $next)
    {
        $module = App('http')->getName();
        $controller = $request->controller(true);
        $action = $request->action(true);

        $rule = Db::name('rule')->where(['module' => $module, 'controller' => $controller, 'action' => $action])->find();

        if ($rule) {
            $payload = JWTAuth::auth();
            $role = $payload['role'];
            $roles = Db::name('role')->whereIn('id', json_decode($role, true))->select();

            if (!in_array($rule['id'], $this->getRoles($roles))) {
                die(json(['code' => 1, 'message' => '没有操作权限！'])->send());
            }

        } else {
            $data = [
                'module' => $module,
                'controller' => $controller,
                'action' => $action,
            ];

            Db::name('rule')->insert($data);

            die(json(['code' => 1, 'message' => '没有操作权限！'])->send());
        }

        return $next($request);
    }

    protected function getRoles($roles)
    {
        $auth = [];
        foreach ($roles as $role) {
            $action = json_decode($role['action'], true);
            foreach ($action as $val) {
                $auth[] = $val;
            }
        }
        return array_unique($auth);
    }
}
